package com.dongbo.recorder.screenrecord.ui.activity;

import android.content.Intent;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dongbo.recorder.screenrecord.AppLpds;
import com.dongbo.recorder.screenrecord.Constants;
import com.dongbo.recorder.screenrecord.R;
import com.dongbo.recorder.screenrecord.adapter.VipAdapter;
import com.dongbo.recorder.screenrecord.base.BaseActivity;
import com.dongbo.recorder.screenrecord.bean.NetResponse;
import com.dongbo.recorder.screenrecord.bean.UserBean;
import com.dongbo.recorder.screenrecord.bean.VipInfo;
import com.dongbo.recorder.screenrecord.bean.WxPayModel;
import com.dongbo.recorder.screenrecord.dialog.PayDialog;
import com.dongbo.recorder.screenrecord.utils.DecryptOrNullBack;
import com.dongbo.recorder.screenrecord.utils.MD5;
import com.dongbo.recorder.screenrecord.utils.PayUtil;
import com.dongbo.recorder.screenrecord.utils.alipay.PayManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Description:
 * @Author: gstory0404@gmail
 * @CreateDate: 2020/5/6 18:16
 */
public class VipActivity extends BaseActivity {

    @BindView(R.id.vip_status)
    TextView vipStatus;
    @BindView(R.id.vip_rv)
    RecyclerView vipRv;
    @BindView(R.id.vip_goods)
    TextView vipGoods;
    @BindView(R.id.vip_pay)
    TextView vipPay;
    @BindView(R.id.vip_back)
    ImageView vipBack;
    @BindView(R.id.iv_select)
    ImageView ivSelect;
    @BindView(R.id.iv_select_2)
    ImageView ivSelect2;
    @BindView(R.id.ll_bottom_0)
    LinearLayout ll_bottom_0;
    @BindView(R.id.ll_bottom_1)
    LinearLayout ll_bottom_1;
    @BindView(R.id.tvXy)
    TextView tvXy;

    private List<VipInfo> list = new ArrayList<>();
    private VipAdapter vipAdapter;
    private String mPrice = "";
    private String mId = "";
    private int mSelect;
    private IWXAPI api;
//    private BasePopupView basePopupView;

    private PayUtil.Builder builder;

    @Override
    protected int getLayout() {
        return R.layout.activity_vip;
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this)
                .fitsSystemWindows(false)
                .keyboardEnable(false)
                .statusBarDarkFont(false)
                .statusBarColor(R.color.transparent)
                .navigationBarColor(R.color.transparent)
                .init();
        initDes();
        initAdapter();
        //获取VIP列表
        vipList();
        setUseEventBus(true);
//        LoadingPop loadingPop = new LoadingPop(this);
//        loadingPop.setProgress("正在加载...");
//        basePopupView = new XPopup.Builder(this)
//                .dismissOnBackPressed(false)
//                .dismissOnTouchOutside(false)
//                .asCustom(loadingPop);

        builder = new PayUtil.Builder(this);
        builder.setListener(new PayUtil.Builder.IAlipayListener() {
            @Override
            public void paySuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(VipActivity.this,"支付成功",Toast.LENGTH_SHORT).show();
                        refreshUserInfo();
                    }
                });
            }

            @Override
            public void startRequest() {

            }

            @Override
            public void endRequest() {

            }

            @Override
            public void requestError() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(VipActivity.this,"支付失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    @Override
    protected void initData() {
//        list.add("VIP永久");
//        list.add("VIP半年");
//        list.add("VIP一个月");
//        vipAdapter.setList(list);

        if (AppLpds.getInstance().getLoginData() != null) {
            if (AppLpds.getInstance().getLoginData().isVip()) {
//                vipStatus.setText("您已是VIP会员，" + AppLpds.getInstance().getLoginData().getVipEndTime() + "到期");
                vipStatus.setText(AppLpds.getInstance().getLoginData().getVipEndTime() + "到期");
                if (AppLpds.getInstance().getLoginData().isVip()) {
                    vipStatus.setText("最尊贵VIP，永久免费使用");
//                    vipStatus.setText("您已是最尊贵VIP，永久免费使用");
//                    ll_bottom_0.setVisibility(View.GONE);
//                    ll_bottom_1.setVisibility(View.GONE);
                }
                vipPay.setText("立即续期");
            } else {
                vipStatus.setText("未开通");
            }
        } else {
            vipStatus.setText("未开通");
        }
    }

    @Override
    protected void initListener() {

    }

    @OnClick({R.id.vip_pay,
            R.id.vip_back,
            R.id.ll_wx,
            R.id.ll_alipay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_wx:
                mSelect = 0;
                ivSelect.setImageResource(R.mipmap.icon_xz_press);
                ivSelect2.setImageResource(R.mipmap.icon_xz);
                break;
            case R.id.ll_alipay:
                mSelect = 1;
                ivSelect2.setImageResource(R.mipmap.icon_xz_press);
                ivSelect.setImageResource(R.mipmap.icon_xz);
                break;
            case R.id.vip_back:
                finish();
                break;
            case R.id.vip_pay:
//                showToast("购买" + vipAdapter.getItem(vipAdapter.getChoose()));
                if (!TextUtils.isEmpty(AppLpds.getInstance().getUserId())) {
//                    openPaySelect();
                    builder.wxPay(mId);
                    if (mSelect == 0) {
//                        onWxPay();

                    } else {
//                        onAlipayPay();
                    }
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
        }
    }

    private void initAdapter() {
        vipRv.setLayoutManager(new GridLayoutManager(this, 3));
        if (vipAdapter == null) {
            vipAdapter = new VipAdapter();
            vipAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    vipAdapter.setChoose(position);
                    mId = list.get(position).getId();
                    mPrice = list.get(position).getPrice();
                    vipGoods.setText(list.get(position).getName() + "：￥" + mPrice);
                }
            });
        }
        vipRv.setAdapter(vipAdapter);
    }

    private void onWxPay() {
        if (TextUtils.isEmpty(mId)) {
            showToast("请选择VIP套餐");
            return;
        }
//        basePopupView.show();
        String token = Constants.SIGN_KEY + "app/mall/generatOrder";
        String sign = MD5.getMessageDigest(token);
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("goodsId", mId)
                .add("uid", AppLpds.getInstance().getUserId())
                .add("appexpId", Constants.APPEXP_ID)
                .add("orderType", "0")
                .add("sign", sign)
                .build();
        Request request = new Request.Builder()
                .url(Constants.BASE_URL + "app/mall/generatOrder")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
//                    basePopupView.dismiss();
                    showToast(e.getMessage());
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String body = response.body().string();
                String data = DecryptOrNullBack.judgeError(body);
//                runOnUiThread(() -> {
//                    basePopupView.dismiss();
//                });
                NetResponse<WxPayModel> info = null;
                try {
                    info = new Gson().fromJson(data, new TypeToken<NetResponse<WxPayModel>>() {
                    }.getType());
                    if (info != null
                            && info.isSuccess()
                            && info.getStatusCode() == 1) {

                        NetResponse<WxPayModel> finalInfo1 = info;
                        runOnUiThread(() -> onPayVipSuccess(finalInfo1));

                    } else {
                        NetResponse finalInfo = info;
                        runOnUiThread(() -> {
                            showToast(finalInfo != null ? finalInfo.getMessage() : "数据有误");
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void vipList() {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("appexpId", Constants.APPEXP_ID)
                .build();
        Request request = new Request.Builder()
                .url(Constants.BASE_URL + "/app/meal/getApp2MealList?appId=" + Constants.APP_ID)
                .addHeader("Authorization", AppLpds.getInstance().getToken())
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    showToast(e.getMessage());
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String body = response.body().string();
//                String data = DecryptOrNullBack.judgeError(body);
                NetResponse<List<VipInfo>> info = null;
                try {
                    info = new Gson().fromJson(body, new TypeToken<NetResponse<List<VipInfo>>>() {
                    }.getType());
                    if (info != null
                            && info.getStatusCode() == 200) {
                        if (info.getData() != null
                                && info.getData().size() > 0) {
                            List<VipInfo> finalInfo = info.getData();
                            runOnUiThread(() -> initVipData(finalInfo));
                        } else {
                            NetResponse finalInfo = info;
                            runOnUiThread(() -> {
//                                showToast(finalInfo != null ? finalInfo.getMessage() : "VIP数据为空");
                            });
                        }
                    } else {
                        NetResponse finalInfo = info;
                        runOnUiThread(() -> {
//                            showToast(finalInfo != null ? finalInfo.getMessage() : "数据有误");
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initVipData(List<VipInfo> mList) {
        list.addAll(mList);
        vipAdapter.setList(list);
        vipAdapter.notifyDataSetChanged();
        mPrice = list.get(0).getPrice();
        mId = list.get(0).getId();
        vipGoods.setText(list.get(0).getName() + "：￥" + mPrice);
    }


    public void onPayVipSuccess(NetResponse<WxPayModel> result) {
        gotoWxPay(result.getData());
    }

    public void gotoWxPay(WxPayModel mWXPay) {
//        if (api == null) {
//            api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID);
//            api.registerApp(Constants.WX_APP_ID);
//        }
//        PayReq req = new PayReq();
//        req.appId = mWXPay.getAppid();
//        req.partnerId = mWXPay.getPartnerid();
//        req.prepayId = mWXPay.getPrepayid();
//        req.sign = mWXPay.getSign();
//        req.nonceStr = mWXPay.getNoncestr();
//        req.timeStamp = mWXPay.getTimestamp();
//        req.packageValue = mWXPay.getPackage();
//        api.sendReq(req);
    }

    @Subscribe
    public void onPayBack(String msg) {
        if (Constants.WXPAY_BROAD.equals(msg)) {
            refreshUserInfo();
        }
//        finish();
    }

    private void refreshUserInfo() {
        OkHttpClient okHttpClient = new OkHttpClient();
        String token = Constants.SIGN_KEY + "app/member/memberInfo";
        String sign = MD5.getMessageDigest(token);
        RequestBody body = new FormBody.Builder()
                .add("uid", AppLpds.getInstance().getUserId())
                .add("sign", sign)
                .add("appexpId", Constants.APPEXP_ID)
                .add("facilityId", AppLpds.getInstance().getDeviceNo())
                .build();
//        equipmentId
        final Request request = new Request.Builder()
                .url(Constants.BASE_URL + "app/member/memberInfo")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    showToast(e.getMessage());
                    finish();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String body = response.body().string();
//                Log.i("TAG__+", body);
                String data = DecryptOrNullBack.judgeError(body);
//                Log.i("TAG__+", data);
                NetResponse<UserBean> info = null;
                try {
                    info = new Gson().fromJson(data, new TypeToken<NetResponse<UserBean>>() {
                    }.getType());
                    if (info != null
                            && info.isSuccess()
                            && info.getStatusCode() == 1) {
                        UserBean finalInfo = info.getData();
                        AppLpds.getMySp().setUserInfo(info.getData());
                        runOnUiThread(() -> finish());
                    } else if (info != null
                            && info.getStatusCode() == 2) {
                        showToast("您的账号在其他设备上登录，请确定是否是您本人操作");
                        runOnUiThread(() -> {
                            AppLpds.getMySp().setUserInfo(null);
                            finish();
                        });
                    } else {
                        NetResponse<UserBean> finalInfo1 = info;
                        runOnUiThread(() -> {
                            showToast(finalInfo1.getMessage());
                            finish();
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(() -> {
                        finish();
                    });
                }

            }
        });
    }

    /**
     * payDialog
     */
    private void openPaySelect() {
        PayDialog mDialog = new PayDialog(this,
                R.style.recharge_pay_dialog,
                new PayDialog.OnDialogEventListener() {

                    @Override
                    public void onWx() {
                        onWxPay();
                    }

                    @Override
                    public void onAlipay() {
                        onAlipayPay();
                    }
                });
        mDialog.show();
    }

    private void onAlipayPay() {
        if (TextUtils.isEmpty(mId)) {
            showToast("请选择VIP套餐");
            return;
        }
//        basePopupView.show();
        String token = Constants.SIGN_KEY + "app/mall/alipayGeneratOrder";
        String sign = MD5.getMessageDigest(token);
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("goodsId", mId)
                .add("uid", AppLpds.getInstance().getUserId())
                .add("appexpId", Constants.APPEXP_ID)
                .add("orderType", "0")
                .add("sign", sign)
                .build();
        Request request = new Request.Builder()
                .url(Constants.BASE_URL + "app/mall/alipayGeneratOrder")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
//                    basePopupView.dismiss();
                    showToast(e.getMessage());
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String body = response.body().string();
                String data = DecryptOrNullBack.judgeError(body);
//                runOnUiThread(() -> {
//                    basePopupView.dismiss();
//                });
//                Log.i("TAG__", data);
                NetResponse<String> info = null;
                try {
                    info = new Gson().fromJson(data, new TypeToken<NetResponse<String>>() {
                    }.getType());
                    if (info != null
                            && info.isSuccess()
                            && info.getStatusCode() == 1) {

                        NetResponse<String> finalInfo1 = info;
                        runOnUiThread(() -> goToZhiFuBao(finalInfo1.getData()));

                    } else {
                        NetResponse finalInfo = info;
                        runOnUiThread(() -> {
                            showToast(finalInfo != null ? finalInfo.getMessage() : "数据有误");
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void goToZhiFuBao(String requestCode) {
        PayManager.play(this,
                requestCode,
                new PayManager.PayResultLinstener() {
                    @Override
                    public void onPaySuccess(final String msg) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                showToast("支付成功！");
                                refreshUserInfo();
//                                finish();
                            }
                        });
                    }

                    @Override
                    public void onPayFailed(final String msg) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                showToast(msg);
                            }
                        });
                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (api != null) {
            api.unregisterApp();
            api = null;
        }
    }

    private void initDes() {
        ClickableSpan clickableSpan1 = new ClickableSpan() {

            @Override
            public void onClick(@NonNull View view) {
                WebActivity.start(VipActivity.this,
                        "会员协议",
                        Constants.VIP);

            }

            @Override
            public void updateDrawState(TextPaint ds) {
                //去掉下划线
                ds.setUnderlineText(false);
            }

        };

        SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
        stringBuilder.append("*点击立即开通即代表您已同意《用户协议》");
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.color_main));
        //设置颜色
        stringBuilder.setSpan(foregroundColorSpan, stringBuilder.toString().indexOf("《用户协议》"), stringBuilder.toString().indexOf("《用户协议》") + 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置点击
        stringBuilder.setSpan(clickableSpan1, stringBuilder.toString().indexOf("《用户协议》"), stringBuilder.toString().indexOf("《用户协议》") + 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvXy.setText(stringBuilder);
        tvXy.setMovementMethod(LinkMovementMethod.getInstance());
        tvXy.setHighlightColor(ContextCompat.getColor(this, R.color.transparent));//点击后的背景颜色为透明
    }

}

